package PlanTree;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;

import exec.util;

public class AlgebraTree {
	
	public String operator="";
	
	public ArrayList<String> columnChoice = new ArrayList<String>();
	public Hashtable<String, String> condition = new Hashtable<String, String>();//column = value
	public String table = "";
	public ArrayList<DataNode> value = null;
	public boolean finish = false;

	public AlgebraTree child = null;
	
	public ArrayList<DataNode> getResult()
	{
		if(value == null)
		{
			if(operator.equals("scan"))
			{
				//read all data from table
				try {
					ArrayList<DataNode> tempresult = util.getAllData(table);//read the data from hbase
					value = tempresult;
					return value;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				}
			}
			if(operator.equals("condition"))
			{
				ArrayList<DataNode> tempresult = new ArrayList<DataNode>();
				ArrayList<DataNode> childResult = child.getResult();
				for(DataNode dn: childResult)//foreach row
				{
					Iterator<String> keys = condition.keySet().iterator();
					while(keys.hasNext())
					{
						String k = keys.next();
						String v = condition.get(k);
						for(String column: dn.attribute)
						{
							if(column.equals(k) && dn.columnValue.get(column).equals(v))
								tempresult.add(dn);
						}
					}
				}
				value = tempresult;
				return value;
			}
			
			if(operator.equals("select"))
			{
				ArrayList<DataNode> tempresult = new ArrayList<DataNode>();
				ArrayList<DataNode> childResult = child.getResult();
				for(DataNode dn: childResult)
				{
					if(columnChoice==null || columnChoice.size()==0)
					{
						tempresult.add(dn);
						continue;
					}
					DataNode chooseDataNode = new DataNode();
					chooseDataNode.attribute = new ArrayList<String>();
					chooseDataNode.columnValue = new Hashtable<String, String>();
					
					//choose several columns
					for(String column:columnChoice)
					{
						if(dn.columnValue.containsKey(column))
						{
							chooseDataNode.attribute.add(column);
							chooseDataNode.columnValue.put(column, dn.columnValue.get(column));
						}
					}
					if(chooseDataNode.attribute.size()>0)
						tempresult.add(chooseDataNode);
				}
				value = tempresult;
				return tempresult;
			}
		}
		else
			return value;
		return null;
	}

}
